from celery.task import task
from TransCarbon import TransCarbon
from TransDely	 import TransDely
from TransRecipe import RecipeXml
from SendMail    import SendMail
import os

CARBON_HOST     = "10.221.173.31"
LOCAL_PATH_IN   = "/data/TransTemp/inbox/"
LOCAL_PATH_OUT  = "/data/TransTemp/outbox/"
SMB_DST_PATH    = "\\\\10.221.173.151\\TransTemp\\outbox\\"


@task
def Trans(filename, smb_path, XmlRecipe, fnupdate=None):
	#
	# Primero se parcea el XML	
	#
	try:
		recipe = RecipeXml(XmlRecipe)
	except:
		return False


	#
	# Cada destino es una parte del total del job, si hay un solo destino representa el 100%, si hay 4 representa el 25%
	#

	

	total_progress    = 0
	

	TotalDestinations = len(recipe.Destination)


	Status = { 'Step' : 'STARTING', 'Done' : total_progress }

	if fnupdate:
		fnupdate(Status)

	#
	# Por Cada destination
	# 

	i = 0
	for recipeDst in recipe.Destination:
		
		#
		# Cada Transcode es el 50% de cada destination
		#
		
		if recipeDst.Transcode:

			#
			# Le establesco un peso de progreso
			#
			
			step_progress = (100.0 / TotalDestinations) / 2 


			Status = { 'Step' : 'TRANSCODING', 'Done' : total_progress }
			if fnupdate:
				fnupdate(Satus)
			
			if recipeDst.Engine == 'Carbon':

				transCarbon = TransCarbon(CARBON_HOST,smb_path,SMB_DST_PATH,LOCAL_PATH_IN,LOCAL_PATH_OUT) 
			
			else:
				return None	


			transCarbon.Start(filename, recipeDst.transcoder)

			files = transCarbon.WaitFinish()	


		else:
			files = [filename]



		if files != []:
		
			total_progress = total_progress + step_progress


			Status = { 'Step' : 'DELIVERING', 'Done': total_progress }

			if fnupdate:
                                fnupdate(Satus)


			#
			# El total de delys representa el otro 50% de cada destination
			#
			TotalDely = len(recipeDst.Dely)

			
			step_progress = ((100.0 / TotalDestinations) / 2) / TotalDely
				

			transDely = TransDely(LOCAL_PATH_OUT)

			for dely in recipeDst.Dely:
	
				ret = transDely.Send(files, dely)
				
				if ret:
					total_progress = total_progress + step_progress
					
					Status = { 'Step' : 'DELIVERING', 'Done': total_progress }
					if fnupdate:
                                		fnupdate(Satus)

				else:
					#
					# Error en el envio
					#
					SendMail(filename)
					return False


		else:
			SendMail(filename)
			return False

		Status = { 'Step' : 'COMPLETED', 'Done': total_progress }
		if fnupdate:
                	fnupdate(Satus)

		#
		# Hacer limpieza de los files
		#
		for f in files:
			os.unlink(LOCAL_PATH_OUT+f)

	SendMail(filename, False)
	return True
			
